import java.io.*;

/**
 * 测试代码，测试一下是不是这个语句有问题，执行不了命令行
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class YOLODetection {

    public static final String YOLO_CD_COMMAND = "cd /root/yolov5-b";
    public static final String YOLO_DETECT_COMMAND = "python detect.py --source data/images/input_image.jpg";

    public static void main(String[] args) throws IOException, InterruptedException {
        // 运行YOLO检测
        System.out.println("进入yolov5文件夹并运行YOLO目标检测...");
        runCommandWithRuntime(YOLO_CD_COMMAND + " && " + YOLO_DETECT_COMMAND);
        System.out.println("目标检测完成。");
    }

    public static void runCommandWithRuntime(String command) throws IOException, InterruptedException {
        // 通过Runtime执行bash命令
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(new String[]{"bash", "-c", command});

        // 输出命令执行过程中的日志
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }

        // 输出错误日志（如果有）
        BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        while ((line = errorReader.readLine()) != null) {
            System.err.println(line);
        }

        // 等待进程完成
        int exitCode = process.waitFor();
        if (exitCode != 0) {
            System.err.println("命令执行失败，退出代码：" + exitCode);
        }
    }
}

